package com.anyisn.anyflickr.shell.view
{
	import com.adobe.webapis.flickr.Photo;
	
	import flash.display.Bitmap;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import org.puremvc.as3.multicore.interfaces.IMediator;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;
	
	import com.anyisn.anyflickr.shell.ShellFacade;
	import com.anyisn.anyflickr.shell.view.components.SlideCanvas;

	public class SlideCanvasMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "SlideCanvasMediator";
		private var _bmp:Bitmap;
		private var _timer:Timer;
		
		public function SlideCanvasMediator(viewComponent:Object)
		{
			super(NAME, viewComponent);
			_timer = new Timer(1500);
			_timer.addEventListener(TimerEvent.TIMER, onTimer);
		}
		
		private function onTimer(e:TimerEvent):void {
			slideCanvas.image.source = _bmp;
			slideCanvas.image.visible = true;
		}
		
		override public function listNotificationInterests():Array {
			return [ShellFacade.PHOTO_LOAD_COMPLETE,
					ShellFacade.STARTED,
					ShellFacade.PAUSED,
					ShellFacade.CONTINUED,
					ShellFacade.ENDED
					];
		}
		
		override public function handleNotification(notification:INotification):void {
			switch(notification.getName()) {
				case ShellFacade.PHOTO_LOAD_COMPLETE:
					var details:Array = notification.getBody() as Array;
					_bmp = details[0] as Bitmap;
					slideCanvas.image.visible = false;
					slideCanvas.photo = details[1] as Photo;
					_timer.stop();
					_timer.start();
					break;
				case ShellFacade.STARTED:
				case ShellFacade.CONTINUED:
					slideCanvas.image.removeEventListener(MouseEvent.CLICK, download);
					break;
				case ShellFacade.PAUSED:
				case ShellFacade.ENDED:
					slideCanvas.image.addEventListener(MouseEvent.CLICK, download);
					break;
			}
		}
		
		private function download(e:MouseEvent):void {
			sendNotification(ShellFacade.PHOTO_PREPARE_DOWNLOAD, slideCanvas.photo);
		}
		
		private function get slideCanvas():SlideCanvas {
			return viewComponent as SlideCanvas;
		}
	}
}